<?php
/*********************************************************************************
* Filename: request_data.php
* 
* This PHP file contains queries which are called using AJAX from the user browser.
* The queries are specified by a type variable that is sent as part of the request.
*
* Author: Phillip Peterson
* Date Created: 09/19/2009
**********************************************************************************/
	include_once "common.php";

	$type = $_REQUEST['type'];

    //This switch statement is used for most all of the AJAX requests used for this web
    //application.  Don't forget to add the break at the end of the case.  If you need
    //to add a new case, add it at the end, before the default case
	switch ($type){

		case 'logout':
			session_start();
			session_unset();
			session_destroy();
			break;

		case 'teamData':
		
			//Store the parameters sent from the request
			$team_id  = $_REQUEST['teamId'];
			$cur_week = $_REQUEST['curWeek'];


			$query   = "SELECT * FROM GAMES WHERE TEAM1 = $team_id OR TEAM2 = $team_id";
			$results = do_query($query,$g_db_name,$g_username);

			break;
		
		case 'weekData':
		
			//Store the parameters sent from the request
			$team_id  = $_REQUEST['teamId'];
			$cur_week = $_REQUEST['curWeek'];

			$query   = "SELECT * FROM GAMES WHERE WEEK = $cur_week AND (TEAM1 = $team_id OR TEAM2 = $team_id) LIMIT 1";
			$results = do_query($query,$g_db_name,$g_username);
			
    		if (mysql_num_rows($results) == 0)
    		    $ret = 'bye';
    		    
    		else {

			    $row = mysql_fetch_assoc($results);

			    $query   = "SELECT * FROM TEAMS WHERE TEAM_ID = {$row['TEAM1']}";
			    $result  = do_query($query,$g_db_name,$g_username);
			    $row_2   = mysql_fetch_assoc($result);
			    $team_1 = $row_2['TEAM_NAME'];

			    $query   = "SELECT * FROM TEAMS WHERE TEAM_ID = {$row['TEAM2']}";
			    $result  = do_query($query,$g_db_name,$g_username);
			    $row_2   = mysql_fetch_assoc($result);
			    $team_2  = $row_2['TEAM_NAME'];

			    $ret  = $row['TEAM1'];
			    $ret .= ",";
			    $ret .= $team_1;
			    $ret .= ",";
			    $ret .= $row['TEAM_1_SCORE'];
			    $ret .= "|";
			    $ret .= $row['TEAM2'];
			    $ret .= ",";
			    $ret .= $team_2;
			    $ret .= ",";
			    $ret .= $row['TEAM_2_SCORE'];
			    
            }   

			echo "$ret";
			break;

		case 'teamLogin':
			$league_id = $_REQUEST['leagueId'];
			$team_name = $_REQUEST['teamName'];
			$password  = $_REQUEST['password'];
			$loggedIn  = $_REQUEST['stayLogged'];
			
			//Query the database for a team ID that matches the credentials given
			$query = "SELECT TEAM_ID,TEAM_NAME,LEAGUE_ID 
					  FROM TEAMS 
					  WHERE LEAGUE_ID = $league_id AND TEAM_NAME = '$team_name' AND TEAM_PWD = '$password'";

			$results  = do_query($query, $g_db_name, $g_username);
			$num_rows = mysql_num_rows($results);
			$row      = mysql_fetch_assoc($results);
			
            $ret = $query_fail;	

			//Check if the team exists.  If so, set the session and session
			//variables which will be used while the user is logged in
			if ($row){
				if ($loggedIn == true) {
					session_set_cookie_params(86400);
				}
				session_start();
				$_SESSION['team_id']   = $row['TEAM_ID'];
				$_SESSION['team_name'] = $row['TEAM_NAME'];
				$_SESSION['league_id'] = $row['LEAGUE_ID'];
				
				$ret = $query_success;
				
			    //Check if team has validated yet
		        $query    = "SELECT TEAM_ID FROM VERIFY WHERE TEAM_ID = {$_SESSION['team_id']}";
    			$results  = do_query($query, $g_db_name, $g_username);
    			//$row      = mysql_fetch_assoc($results);
    			
    			if (mysql_num_rows($results) != 0)
    			    $ret = "no_verify";
            }
            
            echo $ret;

			break;

		case 'rosterUpdate':
			$team_id  = $_REQUEST['teamId'];
			$bench_id = $_REQUEST['benchId'];
			$ice_id   = $_REQUEST['iceId'];

			//Query to sit the ice player
			$query = "UPDATE ROSTER SET POSITION = -1 WHERE PLAYER_ID = $ice_id AND TEAM_ID = $team_id";
			do_query($query, $g_db_name, $g_username);
            //Query to start the bench player
			$query = "UPDATE ROSTER SET POSITION = 1 WHERE PLAYER_ID = $bench_id AND TEAM_ID = $team_id";
			do_query($query, $g_db_name, $g_username);

			break;
			
	    case 'messagePost':

	        $team_id = $_REQUEST['teamId'];
   	        $post    = $_REQUEST['post'];
   	        	    
   			//Query to sit the ice player
			$query = "INSERT INTO SMACKBOARD (TEAM_ID, DATE, MESG) VALUES($team_id,NOW(),'$post')";
			do_query($query, $g_db_name, $g_username);
			
			
		    $date = date("m/d"); 
		    $time = date("g:i a");
		    $name = get_value("team_id",$team_id);
		    $ret = $post . "|" . $date . "|" . $time . "|" . $name;
		    echo "$ret";
	           	        
   	        break;

		case 'checkAvatar':
			$my_id = $_REQUEST['teamId'];
			$query  = "SELECT * FROM TEAMS WHERE TEAM_ID = $my_id";
			$result = do_query($query,$g_db_name,$g_username);
			$fetch  = mysql_fetch_assoc($result);
			$image_id = $fetch['AVATAR'];
			
			if ($image_id == NULL) {
			    $image_id = "default.ico";         						    
			}
			
			echo "$image_id";

			break;
			
		case 'contactEmail':
			$name = $_REQUEST['name'];
			$email = $_REQUEST['email'];
			$subject = $_REQUEST['subject'];
			$message = $_REQUEST['message'];

			$to_email = 'phil12ip@gmail.com';
			$body  = "Contact form submitted by: $name \n";
			$body .= "Email of contact: $email \n\n";
			$body .= "Message \n";
			$body .= "---------------\n";
			$body .= $message;
	
			email_message($subject, $body, $to_email);

			break;			
		
		case 'freeAgent':
			$team        = $_REQUEST['team1'];
			$drop_player = $_REQUEST['player1'];
			$free_player = $_REQUEST['free_agent'];

			//Update the players on this team
			$query = "UPDATE ROSTER SET PLAYER_ID = $free_player 
					  WHERE TEAM_ID = $team AND PLAYER_ID = $drop_player";
            $result = do_query($query, $g_db_name, $g_username);					  
					  

            //Now invalid all other trades involving these players in this league
			$query = "UPDATE PEND_TRADE SET STATUS = 'Declined' 
					  WHERE 
					  ((PLAYER1 = $drop_player AND TEAM1 = $team) 
					  OR (PLAYER2 = $drop_player AND TEAM2 = $team))
					  AND STATUS = 'Pending'";
			$result = do_query($query, $g_db_name, $g_username);            
            
            //Update to show the free agent transaction in the transactions table
            //The second team in the database will be team 0, because there really
            //isn't a second team
            $query = "INSERT INTO PEND_TRADE (TEAM1,TEAM2,PLAYER1,PLAYER2,PROPOSED_ON,STATUS,ACCEPTED_ON)
                      VALUES ($team, $team, $drop_player, $free_player, NOW(), 'Free Agent', NOW())";
		    
			$result = do_query($query, $g_db_name, $g_username);
			
			echo "Free agent successfully added to your team"; 

			break;
			
	    case 'acceptTrade':
	        $trade_id = $_REQUEST['tradeId'];
	        
	        //First check to make sure this user has the authority to accept this trade
	        session_start();
	        $team_id = $_SESSION['team_id'];
	        
	        $query  = "SELECT * FROM PEND_TRADE WHERE PEND_TRADE_ID = $trade_id";
	        $result = do_query($query, $g_db_name, $g_username);
	        
	        $row = mysql_fetch_assoc($result);
	        if ($team_id != $row['TEAM2']){
	            echo "Access Denied.  You do not have permission to modify this trade's state";
	        }
	        else if ($row['STATUS'] != "Pending")
	            echo "This trade is no longer valid";
	        //Otherwise you have the right to modify this trade's state
	        else {
	            //Get the other information about the trade
	            $player1 = $row['PLAYER1'];
	            $player2 = $row['PLAYER2'];
	            $team1   = $row['TEAM1'];
	            $team2   = $team_id;
	            
	            $query = "UPDATE ROSTER SET PLAYER_ID = $player1 WHERE TEAM_ID = $team2 AND PLAYER_ID = $player2";
	            do_query($query, $g_db_name, $g_username);
	            
	            $query = "UPDATE ROSTER SET PLAYER_ID = $player2 WHERE TEAM_ID = $team1 AND PLAYER_ID = $player1";
	            do_query($query, $g_db_name, $g_username);
	            
	            //Update the status of the trade
                $query = "UPDATE PEND_TRADE SET STATUS = 'Accepted', ACCEPTED_ON = NOW() WHERE PEND_TRADE_ID = $trade_id";
	            do_query($query, $g_db_name, $g_username);
	            
	            //Now invalid all other trades involving these players in this league
				$query = "UPDATE PEND_TRADE SET STATUS = 'Declined' 
						  WHERE 
						  ((PLAYER1 = $player1 AND TEAM1 = $team1) 
						  OR (PLAYER1 = $player2 AND TEAM1 = $team2) 
						  OR (PLAYER2 = $player1 AND TEAM2 = $team1)
						  OR (PLAYER2 = $player2 AND TEAM2 = $team2))
						  AND STATUS = 'Pending'";
				$result = do_query($query, $g_db_name, $g_username);
				
			    //Email the team owner which has the trade proposal pending
			    $subject = "Fantasy Broomball: Trade Accepted!";
			    $team2_name = get_value("team_id",$team2);
			    $team1_name = get_value("team_id",$team1);
			    $player1_name = get_value("player_id",$player1);
			    $player2_name = get_value("player_id",$player2);
			
			    $message  = "$team1_name owner,\n\n";
			    $message .= "Your trade proposal has been accepted by $team2_name.  $player2_name has been added to";
			    $message .= "your team, while $player1_name is no longer on your team.  Please login to your team page";
			    $message .= "to manage your updated roster.";
			    $message .= "\n\n";
			    $message .= "------\n";
			    $message .= "MTU Fantasy Broomball";
			
			    $query  = "SELECT OWNER_EMAIL FROM TEAMS WHERE TEAM_ID = $team1";
			    $result = do_query($query, $g_db_name, $g_username);
			    $row = mysql_fetch_assoc($result);
			    $email_id = $row["OWNER_EMAIL"];
			
			    email_message($subject, $message, $email_id);	
			    
			    echo "Trade Accepted";			
				
	        }
	        
	        break;
	        
	    case 'declineTrade':
	        $trade_id = $_REQUEST['tradeId'];
	        
	        //First check to make sure this user has the authority to accept this trade
	        session_start();
	        $team_id = $_SESSION['team_id'];
	        
	        $query  = "SELECT * FROM PEND_TRADE WHERE PEND_TRADE_ID = $trade_id";
	        $result = do_query($query, $g_db_name, $g_username);
	        
	        $row = mysql_fetch_assoc($result);
	        if ($team_id != $row['TEAM2']){
	            echo "Access Denied.  You do not have permission to modify this trade's state";
	        }
	        else if ($row['STATUS'] != "Pending")
	            echo "This trade is no longer valid";
	        //Otherwise you have the right to modify this trade's state
	        else {
	            //Get the other information about the trade
	            $player1 = $row['PLAYER1'];
	            $player2 = $row['PLAYER2'];
	            $team1   = $row['TEAM1'];
	            $team2   = $team_id;
	            
	            //Update the status of the trade
                $query = "UPDATE PEND_TRADE SET STATUS = 'Declined', ACCEPTED_ON = NOW() WHERE PEND_TRADE_ID = $trade_id";
	            do_query($query, $g_db_name, $g_username);
				
			    //Email the team owner which has the trade proposal pending
			    $subject = "Fantasy Broomball: Trade Declined!";
			    $team2_name = get_value("team_id",$team2);
			    $team1_name = get_value("team_id",$team1);
			    $player1_name = get_value("player_id",$player1);
			    $player2_name = get_value("player_id",$player2);
			
			    $message  = "$team1_name owner,\n\n";
			    $message .= "Your trade proposal has been declined by $team2_name.  $player2_name has remains on ";
			    $message .= "your team";
			    $message .= "\n\n";
			    $message .= "------\n";
			    $message .= "MTU Fantasy Broomball";
			
			    $query  = "SELECT OWNER_EMAIL FROM TEAMS WHERE TEAM_ID = $team1";
			    $result = do_query($query, $g_db_name, $g_username);
			    $row = mysql_fetch_assoc($result);
			    $email_id = $row["OWNER_EMAIL"];
			
			    email_message($subject, $message, $email_id);	
			    
			    echo "Trade Declined";
	        }
	        
	        break;
	        
			
		case 'addTrade':
		    $team1_id   = $_REQUEST['team1'];
   		    $team2_id   = $_REQUEST['team2'];
		    $player1_id = $_REQUEST['player1'];
		    $player2_id = $_REQUEST['player2'];
		    
		    //Insert the proposed trade into the database
		    $query = "INSERT INTO PEND_TRADE (TEAM1,TEAM2,PLAYER1,PLAYER2,PROPOSED_ON,STATUS)
		              VALUES ($team1_id,$team2_id,$player1_id,$player2_id,NOW(),'Pending')";
		              
			do_query($query, $g_db_name, $g_username);
			
			//Email the team owner which has the trade proposal pending
			$subject = "Fantasy Broomball: Trade Proposed to You!";
			$team2_name = get_value("team_id",$team2_id);
			$team1_name = get_value("team_id",$team1_id);
			$player1_name = get_value("player_id",$player1_id);
			$player2_name = get_value("player_id",$player2_id);
			
			$message  = "$team2_name owner,\n\n";
			$message .= "The following trade has been proposed to you by $team1_name: $player2_name for $player1_name. ";
			$message .= "You can login to your team homepage to accept/decline the trade.";
			$message .= "\n\n";
			$message .= "------\n";
			$message .= "MTU Fantasy Broomball";
			
			$query  = "SELECT OWNER_EMAIL FROM TEAMS WHERE TEAM_ID = $team2_id";
			$result = do_query($query, $g_db_name, $g_username);
			$row = mysql_fetch_assoc($result);
			$email_id = $row["OWNER_EMAIL"];
			
			email_message($subject, $message, $email_id);
            
            echo "Trade successfully proposed";
            
		    break;

		default:
			echo"None";

	}
?>
